package com.cf.game.group;

import com.cf.game.group.dao.RelationMapper;
import com.cf.game.group.model.Relation;
import com.cf.game.group.vo.RelationVo;
import com.cf.id.SnowflakeId;
import com.cf.location.City;
import com.cf.user.login.model.UserInfo;
import com.cf.user.login.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * boot-awm-RelationService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/28 上午 11:08
 */
@Slf4j
public class RelationService {

    @Autowired
    private City city;

    @Autowired
    private SnowflakeId snowflakeId;

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private UserInfoService userInfoService;

    public List<RelationVo> myRelation(long userId) {
        List<Relation> relations = relationMapper.selectFriendBySelf(userId);
        if (relations == null || relations.size() == 0)
            return Collections.emptyList();
        return relations.stream().map(u -> {
            return new RelationVo(u.getFriend(), u.getFriendName(), u.getFriendHead());
        }).collect(Collectors.toList());
    }


    public boolean isFriend(long sender, long receiver) {
        Relation relation = relationMapper.selectBySelfAndFriend(sender, receiver);
        return relation != null;
    }

    /**
     * @return 自己的未登录的标识
     */
    public void addRelation(long self, long friend, String friendName, String friendHead, String type) {
        Relation relation = new Relation();
        relation.setAddTime(new Date());
        relation.setFriend(friend);
        relation.setId(snowflakeId.nextId());
        relation.setSelf(self);
        relation.setRelationType(type);
        relation.setFriendName(friendName);
        relation.setFriendHead(friendHead);
        this.relationMapper.insert(relation);
    }

    /**
     * 更具Ip获取临时会话Id，需要在浏览器端坐永久存储
     *
     * @param self
     * @param userInfo
     */
    public void addTemporaryRelation(UserInfo self, UserInfo userInfo) {
        String selfName = self.getName();
        //String selfHead = "http://doll-img.oss-cn-shanghai.aliyuncs.com/2017/12/34942974513119232.png";
        String selfHead = self.getHead();
        addRelation(self.getId(), userInfo.getId(), userInfo.getName(), userInfo.getHead(), EnumRelationType.temporary.getType());
        addRelation(userInfo.getId(), self.getId(), selfName, selfHead, EnumRelationType.temporary.getType());
    }


}
